<?php

namespace App\Admin\Actions\Agent\Order;

use App\Models\AgentRechargeRecord;
use App\Models\Order;
use App\Service\WxArticleData;
use Carbon\Carbon;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class OrderStop extends RowAction
{
    protected $selector = '.order-stop';

    public $name = '关闭';


    public function handle(Order $order)
    {

        //检查订单状态：只有投放的订单可以关闭
        if ($order->state != Order::ORDER_STATE_ON) {
            return $this->response()->error('订单状态错误！（非投放状态）')->refresh();
        }
        $agentInfo = $order->adminUser->agent;

        //更新公众号阅读数据
        $read_data = WxArticleData::get($order->url);
        if ($read_data->code == 200) {
            $order->current_read_num = $read_data->read_num;
        } else {
            throw new \Exception($read_data->msg);
        }
        $order->save();

        try {
            DB::beginTransaction();

            //计算订单消耗
            $amount = (($order->expect_read_num - $order->current_read_num) / 1000) * $order->cpm;

            //记录日志
            AgentRechargeRecord::query()->create([
                'admin_user_id' => $agentInfo->admin_user_id,
                'operator' => Auth::guard()->user()->name,
                'amount' => $amount,
                'balance' => $agentInfo->balance + $amount,
                'remark' => '订单关闭，订单余额自动返回账户'
            ]);
            $agentInfo->increment('balance', $amount);//退款
            $order->state = Order::ORDER_STATE_OFF;//修改订单状态为关闭
            $order->stopped_at = Carbon::now()->toDateTimeString();//修改订单结束时间
            $order->save();


            if($order->type == 1){
                //删除曲线订单相关数据

                $redis = Redis::connection();
                $redis->del('curve_order_'.$order->id);//删除曲线订单明细
                $redis->zrem('curve_order_list','curve_order_'.$order->id);//曲线订单集合中移除当前订单
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->success('系统错误！请联系研发！')->refresh();

        }

        return $this->response()->success('关闭成功，余额已退回')->refresh();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default order-stop"></a>
HTML;
    }
}
